package com.express.gateway.spi.proxy.custom.impl;

import com.express.gateway.common.CommonCons;
import com.express.gateway.common.GatewayAttribute;
import com.express.gateway.manage.enums.ContentTypeEnum;
import com.express.gateway.spi.proxy.custom.CustomProxyHandler;
import com.express.gateway.spi.round.AfterHandler;
import io.vertx.core.Future;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;

/**
 * 获得服务器时间戳
 *
 * @author flower
 */
public class GetServerUnixTimestampProxyHandler implements CustomProxyHandler {
    /**
     * 返回结果定义,默认占位符为$(val)
     */
    private String resultFormat = "$(val)";
    /**
     * 路由器要结束了还是讲任务传到下一个处理器,默认为结束
     */
    private boolean isNext = false;
    /**
     * 默认的返回类型为json_utf8
     */
    private String contentType = ContentTypeEnum.JSON_UTF8.val();

    @Override
    public void handle(RoutingContext rct) {
        String result = resultFormat.replace("$(val)", Long.toString(System.currentTimeMillis()));
        if (isNext) {
            rct.put(AfterHandler.PREV_IS_SUCCESS_KEY, Future.<Boolean>succeededFuture(true));// 告诉后置处理器当前操作成功执行
            rct.response().putHeader(CommonCons.SERVER, GatewayAttribute.FULL_NAME).putHeader(CommonCons.CONTENT_TYPE,
                    contentType);
            rct.next();
            return;
        }

        if (rct.response().ended()) {
            return;
        }
        rct.response().putHeader(CommonCons.SERVER, GatewayAttribute.FULL_NAME).putHeader(CommonCons.CONTENT_TYPE, contentType).end(result);
    }

    /**
     * 实例化一个返回服务器时间戳处理器<br>
     * option.resultFormat 格式化返回值,$(val)为值占位,默认值$(val)<br>
     * option.isNext 是否还有后置处理器,默认false, true处理请求后next,false响应请求<br>
     * option.contentType 返回的content-type 类型 <@ ContentTypeEnum.JSON_UTF8><br>
     *
     * @param option 处理器参数
     */
    public GetServerUnixTimestampProxyHandler(JsonObject option) {
        if (option.getValue("resultFormat") instanceof String) {
            this.resultFormat = option.getString("resultFormat");
        }
        if (option.getValue("isNext") instanceof Boolean) {
            this.isNext = option.getBoolean("isNext");
        }
        if (option.getValue("contentType") instanceof String) {
            this.contentType = option.getString("contentType");
        }
    }

}
